package cn.ant.Client;

import cn.ant.utils.ChannelUtil;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

/**
 * 生产者（生产任务）
 *
 * @author Anhui AntLaddie <a href="https://juejin.cn/user/4092805620185316">(掘金蚂蚁小哥)</a>
 * @version 1.0
 **/
public class Producer {

    // 通过日志管理器获取Logger对象
    static Logger logger = LogManager.getLogger(Producer.class);
    // 直接交换机名称
    public static final String NORMAL_EXCHANGE = "NormalExchange";
    // 路由Key
    public static final String NORMAL_KEY = "NormalKey";

    public static void main(String[] args) throws IOException {
        // 通过工具类获取一个信道
        Channel channel = ChannelUtil.getChannel();
        // 创建名称为"NormalExchange"的直接交换机
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT,
                true, false, false, null);

        // 设置需要发送的内容，并循环发送
        List<String> msgContentList = Arrays.asList("a11", "b22", "a33", "b44", "a55");
        msgContentList.forEach(e -> {
            try {
                // 创建消息，并每隔2秒发送消息到NORMAL_EXCHANGE交换机
                byte[] msg = ("[消息：" + e + "]").getBytes(StandardCharsets.UTF_8);
                Thread.sleep(2000);
                // 消息参数配置信息；expiration过期时间10秒、deliveryMode=2为消息持久化
                AMQP.BasicProperties properties = new AMQP.BasicProperties().builder()
                        // .expiration("10000")
                        .deliveryMode(2).build();
                // 发送消息
                channel.basicPublish(NORMAL_EXCHANGE, NORMAL_KEY, properties, msg);
                logger.info("生产者发送了一条消息，消息内容为：{}", new String(msg));
            } catch (Exception ex) {
                logger.error("生产者消息发送失败×××");
                throw new RuntimeException(ex.getMessage());
            }
        });
        logger.info("生产者消息发送完成...");
    }
}
